<template>
  <div>
    <div>
      <el-button @click="addRow" type="primary">增加行</el-button>
      <el-button @click="addCol" type="primary">增加列</el-button>
      <el-button @click="mergeCells" type="primary">合并单元格</el-button>
      <el-button @click="splitCells" type="primary">拆分单元格</el-button>
      <el-button @click="undo" type="warning" :disabled="history.length === 0">回退</el-button>
      <el-button @click="save" type="primary">保存</el-button>
      <el-button @click="exportJson" type="success">导出JSON</el-button>
      <el-button @click="view" type="success">预览</el-button>
    </div>
    <div v-if="dragState.startRow !== null && dragState.endRow !== null" style="margin-top: 10px;">
      选中区域:{{generateColumnLabel(dragState.startCol)+''+(dragState.startRow+1)}}:{{generateColumnLabel(dragState.endCol)+''+(dragState.endRow+1)}}
  
      <!-- {{ selectedRowCount }} 行 × {{ selectedColCount }} 列 -->
    </div>
    <div class="table-container">
      <table border="1">
      <thead>
        <tr>
          <th style="min-width:50px!important;max-width:50px!important;">#</th>
          <th v-for="(col, colIndex) in cols" :key="colIndex" @mouseenter="hoverCol = colIndex" @mouseleave="hoverCol = null">
            {{ generateColumnLabel(colIndex) }}
            <div class="resize-handle-r" @mousedown="(e) => startResizeCol(e, colIndex)"></div>
            <span v-if="hoverCol === colIndex" class="delete-icon" @click="deleteCol(colIndex)">✖</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
          <td style="min-width:50px!important;max-width:50px!important;" @mouseenter="hoverRow = rowIndex" @mouseleave="hoverRow = null">
            {{ rowIndex + 1 }}
            <div class="resize-handle-c" @mousedown="(e) => startResizeRow(e, rowIndex)"></div>
            <span v-if="hoverRow === rowIndex" class="delete-icon" @click="deleteRow(rowIndex)">✖</span>
          </td>
          <template v-for="(cell, colIndex) in row" :key="colIndex">
            <td v-if="shouldDisplayCell(rowIndex, colIndex)"
                @click="editCell(rowIndex, colIndex,cell)"
                :_index="generateColumnLabel(colIndex)+(rowIndex+1)"
                :rowspan="getMergedSpan(rowIndex, colIndex, 'row')"
                :colspan="getMergedSpan(rowIndex, colIndex, 'col')"
                :align="cell.align || 'left'"
                :style="'font-size:'+cell.fontSize+'px'"
                :class="{ 
                  'selected-range': isSelected(rowIndex, colIndex),
                  'merged-cell': isMergedCell(rowIndex, colIndex)
                }"
                @mousedown="startDragSelection(rowIndex, colIndex)"
                @mouseover="handleDragSelection(rowIndex, colIndex)">
              <input v-if="cell.tag !== 'text'" :value="getCellValue(rowIndex, colIndex)"
                    @input="updateCellValue(rowIndex, colIndex, $event.target.value)"
                    
                    style="width: 100%;" />
              <span :style="'width:100%;text-align:'+cell.align+';'" v-if="cell.tag == 'text'">{{ getCellValue(rowIndex, colIndex) }}</span>
            </td>
          </template>
        </tr>
      </tbody>
      <!-- <tbody>
        <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
          <td>{{ rowIndex + 1 }}</td>
          <td v-for="(cell, colIndex) in row" :_index="generateColumnLabel(colIndex)+(rowIndex+1)" :key="colIndex" 
              :class="{ 'selected-range': isSelected(rowIndex, colIndex) }">
            <input v-model="cell.value" @click="editCell(rowIndex, colIndex)" style="width: 100%;" />
          </td>
        </tr>
      </tbody> -->
    </table>
    </div>
    <div
      v-if="showEditor"
      ref="editorRef"
      class="floating-editor"
      :style="{ top: `${editorPosition.y}px`, left: `${editorPosition.x}px` }"
      
    >
    <div class="editor-header" @mousedown="startDrag">
        <el-button type="text" @click="showEditor = false">✖</el-button>
      </div>
    <el-tabs v-model="activeTabs" class="demo-tabs" @tab-click="handleClick">
     
      <el-tab-pane label="单元格属性" name="first"> 
        <el-form label-width="140px">
          <el-form-item label="类型">
            <el-select v-model="selectedCellData.tag">
              <el-option label="只读文本" value="text" />
              <el-option label="输入框" value="input" />
              <el-option label="下拉框" value="select" />
              <el-option label="树形选择" value="tree" />
              <el-option label="时间" value="time" />
              <el-option label="日期" value="date" />
              <el-option label="时间日期" value="datetime" />
              <el-option label="复选框" value="checkbox" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag=='select' || selectedCellData.tag=='tree' || selectedCellData.tag=='checkbox'" label="选项数据类型">
            <el-select  v-model="selectedCellData.optionsDataType">
              <el-option label="字典" value="dict" />
              <el-option label="接口" value="api" />
              <el-option label="静态数据" value="static" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='dict'" label="字典Code">
            <el-input v-model="selectedCellData.dictCode" />
          </el-form-item>
          <el-form-item  label="选项数据接口地址" v-if="selectedCellData.optionsDataType=='api'">
            <el-input v-model="selectedCellData.optionsApiUrl" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据API类型">
            <el-select v-model="selectedCellData.optionsApiType">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据API参数">
            <el-input type="textarea" v-model="selectedCellData.optionsApiParams" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据取值位置">
            <el-input type="textarea" v-model="selectedCellData.optionsApiGetPos" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据选项名">
            <el-input type="textarea" v-model="selectedCellData.optionsApiLabel" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据选项值">
            <el-input type="textarea" v-model="selectedCellData.optionsApiValue" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据子项键名">
            <el-input type="textarea" v-model="selectedCellData.optionsApiChildrenKey" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='static'" label="静态选项数据">
            <el-input type="textarea" v-model="selectedCellData.staticOptsData" />
          </el-form-item><el-form-item v-if="selectedCellData.optionsDataType=='dict'" label="字典Code">
            <el-input v-model="selectedCellData.dictCode" />
          </el-form-item>
          <el-form-item  label="选项数据接口地址" v-if="selectedCellData.optionsDataType=='api'">
            <el-input v-model="selectedCellData.optionsApiUrl" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据API类型">
            <el-select v-model="selectedCellData.optionsApiType">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据API参数">
            <el-input type="textarea" v-model="selectedCellData.optionsApiParams" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据取值位置">
            <el-input type="textarea" v-model="selectedCellData.optionsApiGetPos" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据选项名">
            <el-input type="textarea" v-model="selectedCellData.optionsApiLabel" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据选项值">
            <el-input type="textarea" v-model="selectedCellData.optionsApiValue" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.optionsDataType=='api'" label="选项数据子项键名">
            <el-input type="textarea" v-model="selectedCellData.optionsApiChildrenKey" />
          </el-form-item>
          <el-form-item label="内容">
            <el-input  v-model="selectedCellData.value" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="默认值">
            <el-input v-model="selectedCellData.defaultValue" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="字段 Key">
            <el-input v-model="selectedCellData.__vModel__" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="字段 Label">
            <el-input v-model="selectedCellData.label" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="字段类型">
            <el-select v-model="selectedCellData.modelType"> 
              <el-option value="1" label="字符串"></el-option>
              <el-option value="2" label="数字"></el-option>
              <el-option value="3" label="日期"></el-option>
              <el-option value="4" label="大文本"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="字段长度">
            <el-input v-model="selectedCellData.maxlength" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.modelType=='3'"  label="日期格式">
            <el-input v-model="selectedCellData['value-format']" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.tag!='text'" label="是否必填">
            <el-checkbox v-model="selectedCellData.required">必填</el-checkbox>
          </el-form-item>
          <el-form-item label="对齐方式">
            <el-select v-model="selectedCellData.align">
              <el-option label="左对齐" value="left" />
              <el-option label="居中对齐" value="center" />
              <el-option label="右对齐" value="right" />
            </el-select>
          </el-form-item>
          <el-form-item label="背景色">
            <el-color-picker v-model="selectedCellData.bgColor" />
          </el-form-item>
          <el-form-item label="单元格宽度">
            <el-input v-model="selectedCellData.cellWidth" />
          </el-form-item>
          <el-form-item label="字体大小">
            <el-input v-model="selectedCellData.fontSize" />
          </el-form-item>
          
          
          <el-form-item label="是否远程数据">
            <el-checkbox v-model="selectedCellData.isRemoteData">远程数据</el-checkbox>
          </el-form-item>
          
          
          <el-form-item v-if="selectedCellData.isRemoteData" label="远程数据API地址">
            <el-input v-model="selectedCellData.api" />
          </el-form-item>
          <el-form-item v-if="selectedCellData.isRemoteData" label="远程数据API类型">
            <el-select v-model="selectedCellData.apiType">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              </el-select>
          </el-form-item>
          <el-form-item v-if="selectedCellData.isRemoteData" label="远程数据API参数">
            <el-input type="textarea" v-model="selectedCellData.apiParams" />
          </el-form-item>
          <el-form-item label="公式">
            <el-input type="textarea" v-model="selectedCellData.formula" />
          </el-form-item>
          <el-form-item label="公式依赖项">
            <el-input type="textarea" v-model="selectedCellData.formulaDepends" />
          </el-form-item>
          <el-form-item label="是否只读">
            <el-checkbox v-model="selectedCellData.readOnly">只读</el-checkbox>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="表单属性" name="second">
        <el-form label-width="140px">
          <el-form-item label="表单名称">
            <el-input v-model="formInfo.formName" />
          </el-form-item>
          <el-form-item label="表单模型">
            <el-input v-model="formInfo.formModel" />
          </el-form-item>
          <el-form-item label="表单宽度">
            <el-input v-model="formInfo.formWidth" />
          </el-form-item>
          <el-form-item label="单元格最小宽度">
            <el-input v-model="formInfo.cellMinWidth" />
          </el-form-item>
          <el-form-item label="单元格最大宽度">
            <el-input v-model="formInfo.cellMaxWidth" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="服务配置" name="third">
        <el-form label-width="140px">
          <el-form-item label="服务器地址(IP/域名)">
            <el-input v-model="formInfo.serveUrl" />
          </el-form-item>
          <el-form-item label="端口号">
            <el-input v-model="formInfo.servePort" />
          </el-form-item>
          <el-form-item label="代理前缀">
            <el-input v-model="formInfo.proxyPrefix" />
          </el-form-item>
          </el-form>
      </el-tab-pane>
    </el-tabs>
      
    </div>
    <!-- 预览 -->
     <el-dialog v-model="visibleRender">
        <Render :data="currentJson" :key="changeRenderIndex" />
     </el-dialog>
     
  </div>
</template>

<script setup>
import { ref, reactive, computed,onUnmounted,watch} from 'vue';
import {ElButton, ElForm, ElFormItem, ElSelect, ElOption, ElInput, ElCheckbox } from 'element-plus';
import Render from "./render.vue"
import json from "./assets/test.json"
import json3 from "./assets/test3.json"
import json4 from "./assets/test4.json"
import json5 from "./assets/test5.json"
import json7 from "./assets/test7.json"
import jsonyb from "./assets/testyb.json"
const currentJson = ref(null);
const rows = ref(10);
const cols = ref(10);
const showEditor = ref(false);
const visibleRender = ref(false);
const editorRef = ref(null);
const editorPosition = reactive({ x: 300, y: 200 });
const activeTabs = ref('first');
const changeRenderIndex = ref(0);
const currentCell = ref({
  row:0,
  col:0
});
const formInfo = ref({
  formName:"",
  formModel:"",
  formWidth:"600",
  cellMinWidth:"80"
});
// 行高和列宽状态
const rowHeights = ref(Array.from({ length: rows.value }, () => 40)); // 默认行高40px
const colWidths = ref(Array.from({ length: cols.value }, () => 120)); // 默认列宽120px

// 操作历史记录
const history = ref([]);
const MAX_HISTORY_LENGTH = 5; // 最大历史记录长度

const generateColumnLabel = (index) => {
  let label = "";
  while (index >= 0) {
    label = String.fromCharCode((index % 26) + 65) + label;
    index = Math.floor(index / 26) - 1;
  }
  return label;
};

const dragState = reactive({
  isDragging: false,
  startRow: null,
  startCol: null,
  endRow: null,
  endCol: null
});


const isSelected = (rowIndex, colIndex) => {
  if (dragState.startRow !== null && dragState.startCol !== null &&
      dragState.endRow !== null && dragState.endCol !== null) {
    return (
      rowIndex >= Math.min(dragState.startRow, dragState.endRow) &&
      rowIndex <= Math.max(dragState.startRow, dragState.endRow) &&
      colIndex >= Math.min(dragState.startCol, dragState.endCol) &&
      colIndex <= Math.max(dragState.startCol, dragState.endCol)
    );
  }
  return false;
};

const tableData = ref(Array.from({ length: rows.value }, () =>
  Array.from({ length: cols.value }, () => ({
    value: '',
    defaultValue: '',
    modelType: '1', // 字段类型，默认为字符串
    optionsDataType: '', // 选项数据类型
    dictCode: '', // 字典code
    optionsApiUrl: '', // 选项数据接口地址
    optionsApiType: '', // 选项数据API类型
    optionsApiParams:'', // 选项数据API参数
    optionsApiGetPos:'', // 选项数据API获取位置
    optionsApiLabel:'', // 选项数据选项名
    optionsApiValue:'', // 选项数据选项值
    staticOptsData: '', // 静态选项数据
    cellWidth: '', // 单元格宽度
    optionsApiChildrenKey:'', // 选项数据API子项key


    api: '', // 远程数据API地址
    apiType: '', // 远程数据API类型
    apiParams: '', // 远程数据API参数
    __vModel__: '', // 字段 Key
    isRemoteData: false, // 是否远程数据
    required: false, // 是否必填
    tag: 'text',// 控件类型
    key: '',
    label: '',
    formula: '',
    formulaDepends:'',//公式依赖项
    readOnly: false
  }))
));

const selectedCell = reactive({ row: null, col: null });
// 合并单元格的数据
const mergedCells = ref([]);



const handleClick = (v)=>{
  console.log(v)
}


const selectedCellData = computed(() => {
  if (selectedCell.row !== null && selectedCell.col !== null) {
    return tableData.value[selectedCell.row][selectedCell.col];
  }
  return {};
});

const editCell = (row, col,cell) => {
  console.log(cell,'cell')
  selectedCell.row = row;
  selectedCell.col = col;
  showEditor.value = true;
};

const addRow = () => {
  tableData.value.push(Array.from({ length: cols.value }, () => ({
    value: '',
    defaultValue: '',
    modelType: '1', // 字段类型，默认为字符串
    optionsDataType: '', // 选项数据类型
    dictCode: '', // 字典code
    optionsApiUrl: '', // 选项数据接口地址
    optionsApiType: '', // 选项数据API类型
    optionsApiParams:'', // 选项数据API参数
    optionsApiGetPos:'', // 选项数据API获取位置
    optionsApiLabel:'', // 选项数据选项名
    optionsApiValue:'', // 选项数据选项值
    optionsApiChildrenKey:'', // 选项数据API子项key
    cellWidth: '', // 单元格宽度
    apiParams: '', // 选项数据API参数
    staticOptsData: '', // 静态选项数据
    api: '', // 远程数据API地址
    apiType: '', // 远程数据API类型
    apiParams: '', // 远程数据API参数
    __vModel__: '', // 字段 Key
    isRemoteData: false, // 是否远程数据
    required: false, // 是否必填
    tag: 'text',// 控件类型
    label: '',
    formula: '',//公式
    formulaDepends:'',//公式依赖项
    readOnly: false

  })));
  rows.value++;
};

const addCol = () => {
  saveStateToHistory(); // 保存当前状态到历史记录
  tableData.value.forEach(row => {
    row.push({
      value: '',
      type: 'text',
      key: '',
      label: '',
      formula: '',
      readOnly: false
    });
  });
  cols.value++;
};

// const exportJson = () => {
//   console.log(tableData.value)
//   //console.log(JSON.stringify(tableData.value, null, 2));
// };
const selectedRowCount = computed(() => {
  console.log(dragState,'dragState')
  if (dragState.startRow !== null && dragState.endRow !== null) {
    return Math.abs(dragState.endRow - dragState.startRow) + 1;
  }
  return 0;
});

const selectedColCount = computed(() => {
  if (dragState.startCol !== null && dragState.endCol !== null) {
    return Math.abs(dragState.endCol - dragState.startCol) + 1;
  }
  return 0;
});
let dragOffset = { x: 0, y: 0 };

const startDrag = (event) => {
  if (!editorRef.value) return;

  dragOffset = {
    x: event.clientX - editorPosition.x,
    y: event.clientY - editorPosition.y,
  };

  document.addEventListener("mousemove", doDrag);
  document.addEventListener("mouseup", stopDrag);
};
const doDrag = (event) => {
  editorPosition.x = event.clientX - dragOffset.x;
  editorPosition.y = event.clientY - dragOffset.y;
};

const stopDrag = () => {
  document.removeEventListener("mousemove", doDrag);
  document.removeEventListener("mouseup", stopDrag);
};
// 新增合并单元格相关状态
//const mergedCells = ref([]);
const isDragging = ref(false);

// 合并单元格实现
const mergeCells = () => {
  const { startRow, startCol, endRow, endCol } = dragState;
  if (startRow === null || startCol === null) return;

  const minRow = Math.min(startRow, endRow);
  const maxRow = Math.max(startRow, endRow);
  const minCol = Math.min(startCol, endCol);
  const maxCol = Math.max(startCol, endCol);

  // 检查是否与其他合并区域重叠
  const hasOverlap = mergedCells.value.some(merged => (
    minRow <= merged.endRow &&
    maxRow >= merged.startRow &&
    minCol <= merged.endCol &&
    maxCol >= merged.startCol
  ));

  if (hasOverlap) {
    ElMessage.error('不能与现有合并区域重叠');
    return;
  }
  // 保存当前状态到历史记录
  saveStateToHistory();
  // 添加新合并区域
  mergedCells.value.push({
    startRow: minRow,
    startCol: minCol,
    endRow: maxRow,
    endCol: maxCol
  });

  // 清除选区状态
  resetDragState();
};
// 拆分单元格
const splitCells = () => {
  const { startRow, startCol } = dragState;
  if (startRow === null || startCol === null) return;

  // 找到包含当前单元格的合并区域
  const mergedIndex = mergedCells.value.findIndex(merged => 
    startRow >= merged.startRow &&
    startRow <= merged.endRow &&
    startCol >= merged.startCol &&
    startCol <= merged.endCol
  );

  if (mergedIndex === -1) {
    ElMessage.warning('当前单元格未合并');
    return;
  }
   // 保存当前状态到历史记录
   saveStateToHistory();
  // 移除合并区域
  mergedCells.value.splice(mergedIndex, 1);

  // 清除选区状态
  resetDragState();
};

// 保存当前状态到历史记录
const saveStateToHistory = () => {
  const state = {
    tableData: JSON.parse(JSON.stringify(tableData.value)),
    mergedCells: JSON.parse(JSON.stringify(mergedCells.value)),
    rowHeights: JSON.parse(JSON.stringify(rowHeights.value)),
    colWidths: JSON.parse(JSON.stringify(colWidths.value)),
    rows: rows.value,
    cols: cols.value
  };

  history.value.push(state);

  // 限制历史记录的最大长度
  if (history.value.length > MAX_HISTORY_LENGTH) {
    history.value.shift();
  }
};

// 回退操作
const undo = () => {
  if (history.value.length === 0) return;

  const previousState = history.value.pop();

  tableData.value = previousState.tableData;
  mergedCells.value = previousState.mergedCells;
  rowHeights.value = previousState.rowHeights;
  colWidths.value = previousState.colWidths;
  rows.value = previousState.rows;
  cols.value = previousState.cols;
};

// 监听 tableData 的变化
watch(
  tableData,
  (newValue, oldValue) => {
    // 如果变化是由回退操作引起的，则不保存历史记录
    if (history.value.some(state => state.tableData === newValue)) return;

    saveStateToHistory();
  },
  { deep: true }
);

// 重置拖拽选择状态
const resetDragState = () => {
  dragState.startRow = null;
  dragState.startCol = null;
  dragState.endRow = null;
  dragState.endCol = null;
};
// 单元格显示判断
const shouldDisplayCell = (row, col) => {
  // 如果是合并区域的起始单元格则显示
  if (isMergeStartCell(row, col)) return true;
  // 如果被其他合并区域包含则不显示
  return !isInMergedRange(row, col);
};

// 获取单元格跨度
const getMergedSpan = (row, col, type) => {
  const merged = findMergedCell(row, col);
  if (!merged || !isMergeStartCell(row, col)) return 1;
  return type === 'row' 
    ? merged.endRow - merged.startRow + 1 
    : merged.endCol - merged.startCol + 1;
};

// 获取单元格值（处理合并单元格）
const getCellValue = (row, col) => {
  const merged = findMergedCell(row, col);
  if (merged) {
    return tableData.value[merged.startRow][merged.startCol].value;
  }
  return tableData.value[row][col].value;
};

// 更新单元格值（处理合并单元格）
const updateCellValue = (row, col, value) => {
  const merged = findMergedCell(row, col);
  if (merged) {
    tableData.value[merged.startRow][merged.startCol].value = value;
  } else {
    tableData.value[row][col].value = value;
  }
};

// 辅助方法
const findMergedCell = (row, col) => {
  return mergedCells.value.find(merged => 
    row >= merged.startRow &&
    row <= merged.endRow &&
    col >= merged.startCol &&
    col <= merged.endCol
  );
};

const isMergeStartCell = (row, col) => {
  const merged = findMergedCell(row, col);
  return merged && row === merged.startRow && col === merged.startCol;
};
const isMergedCell = (row, col) => {
  return mergedCells.value.some(merged => 
    row >= merged.startRow &&
    row <= merged.endRow &&
    col >= merged.startCol &&
    col <= merged.endCol
  );
};
const isInMergedRange = (row, col) => {
  return mergedCells.value.some(merged => 
    row >= merged.startRow &&
    row <= merged.endRow &&
    col >= merged.startCol &&
    col <= merged.endCol &&
    !(row === merged.startRow && col === merged.startCol)
  );
};

// 修改后的拖拽选择逻辑
const startDragSelection = (row, col) => {
  let rowIndex = row+1;
  let colIndex = generateColumnLabel(col);
  currentCell.value = { row:rowIndex, col:colIndex };
  isDragging.value = true;
  dragState.startRow = row;
  dragState.startCol = col;
  dragState.endRow = row;
  dragState.endCol = col;
};

const handleDragSelection = (row, col) => {
  if (isDragging.value) {
    dragState.endRow = row;
    dragState.endCol = col;
  }
};

// 在window添加mouseup事件监听
window.addEventListener('mouseup', () => {
  isDragging.value = false;
});

// 导出时包含合并信息
const exportJson = () => {
  const exportData = {
    ...formInfo.value,
    data: tableData.value,
    mergedCells: mergedCells.value
  };
  currentJson.value = exportData;
  console.log(exportData,'final data')
  //console.log(JSON.stringify(exportData, null, 2));
};

const save = ()=>{
  const exportData = {
    data: tableData.value,
    mergedCells: mergedCells.value
  };
  console.log(exportData, 'exportData');
  let fields = [];
  exportData.data.map(item=>{
    item.map(filed=>{
      fields.push({
        __vModel__:filed.__vModel__,
        __config__:{
          value:filed.value,
          defaultValue:filed.defaultValue,
          label:filed.label,
          modelType: filed.modelType,
          optionsDataType:filed.optionsDataType,
          dictCode: filed.dictCode,
          optionsApiUrl: filed.optionsApiUrl,
          optionsApiType:filed.optionsApiType,
          apiParams: filed.apiParams,
          staticOptsData:filed.staticOptsData,
          api: filed.api,
          apiType:filed.apiType,
          apiParams:filed.apiParams,
          isRemoteData:filed.isRemoteData,
          required:filed.required,
          tag:filed.tag,
          formula:filed.formula,
          readOnly:filed.readOnly,
          align:filed.align,
          fontSize:filed.fontSize
        }
      })
    })
    
  })
  let data = {
    ...formInfo.value,
    fields: fields,
    mergedCells: exportData.mergedCells,
  }
  console.log(data,'final data')
}

// 拖拽调整状态
const resizeState = reactive({
  isResizing: false,
  target: null, // 'row' 或 'col'
  index: null, // 行或列的索引
  startPos: null, // 拖拽起始位置
  startSize: null // 拖拽起始尺寸
});

// 开始调整列宽
const startResizeCol = (e, colIndex) => {
  resizeState.isResizing = true;
  resizeState.target = 'col';
  resizeState.index = colIndex;
  resizeState.startPos = e.clientX;
  resizeState.startSize = colWidths.value[colIndex];

  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
};

// 开始调整行高
const startResizeRow = (e, rowIndex) => {
  resizeState.isResizing = true;
  resizeState.target = 'row';
  resizeState.index = rowIndex;
  resizeState.startPos = e.clientY;
  resizeState.startSize = rowHeights.value[rowIndex];

  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
};

// 处理拖拽调整
const handleResize = (e) => {
  if (!resizeState.isResizing) return;

  if (resizeState.target === 'col') {
    // 调整列宽
    const delta = e.clientX - resizeState.startPos;
    colWidths.value[resizeState.index] = Math.max(50, resizeState.startSize + delta); // 最小宽度50px
  } else if (resizeState.target === 'row') {
    // 调整行高
    const delta = e.clientY - resizeState.startPos;
    rowHeights.value[resizeState.index] = Math.max(30, resizeState.startSize + delta); // 最小高度30px
  }
};

// 停止拖拽调整
const stopResize = () => {
  resizeState.isResizing = false;
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
};

// 鼠标悬浮状态
const hoverRow = ref(null); // 当前悬浮的行索引
const hoverCol = ref(null); // 当前悬浮的列索引
// 删除指定行
const deleteRow = (rowIndex) => {
  if (rows.value <= 1) {
    ElMessage.warning('至少保留一行');
    return;
  }
  saveStateToHistory(); // 保存当前状态到历史记录
  tableData.value.splice(rowIndex, 1); // 删除指定行
  rowHeights.value.splice(rowIndex, 1); // 删除对应行高
  rows.value--;
};

// 删除指定列
const deleteCol = (colIndex) => {
  if (cols.value <= 1) {
    ElMessage.warning('至少保留一列');
    return;
  }
  saveStateToHistory(); // 保存当前状态到历史记录
  tableData.value.forEach(row => {
    row.splice(colIndex, 1); // 删除指定列
  });
  colWidths.value.splice(colIndex, 1); // 删除对应列宽
  cols.value--;
};

const view = ()=>{
  exportJson();
  changeRenderIndex.value++
  visibleRender.value = true;
}

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
});
</script>

<style lang="scss" scoped>
.selected {
  background-color: #f0f8ff;
  border: 1px solid #409eff;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 0!important;
    border: 1px solid #ddd;  // Add borders to cells
  }

  .cell {
    padding: 0!important;
    border: 1px solid #ddd;  // Ensures the cell borders appear
  }
}

input {
  border: none;
  width: 100%;
  height: 100%;
  padding: 8px;
  box-sizing: border-box;
}

.selected-range {
  background-color: rgba(64, 158, 255, 0.3) !important; /* Highlight selected range */
  border: 1px solid #409eff !important;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;  // Allow scrolling horizontally if table overflows
}

table {
  width: auto;
  border-collapse: collapse;  // Merge borders for a single-line effect
  table-layout: fixed; /* 固定布局，确保宽度生效 */
}

thead {
  background-color: #f5f5f5;  // Light background for header
}

th, td {
  //text-align: center;  // Center the content in header and cells
  padding: 0px;
  border: 1px solid #ddd;  // Single line borders for cells and header
  font-size: 14px;
    min-width:120px;
}

th {
  background-color: #e5e5e5;  // Slightly darker background for header
  font-weight: bold;
}

.floating-editor {
  position: fixed;
  width: 500px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 15px;
  z-index: 1000;
}

.editor-header {
  display: flex;
  justify-content:flex-end;
  align-items: center;
  font-weight: bold;
  cursor: move;
  background: #f5f5f5;
  padding: 5px 10px;
  border-bottom: 1px solid #ddd;
}

.floating-editor .el-form-item {
  margin-bottom: 10px;
}
.merged-cell {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}

.selected-range {
  background-color: rgba(64, 158, 255, 0.3);
  border: 1px solid #409eff !important;
}
.resize-handle-r {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 3px;
  height:100%;
  background-color: #409eff;
  cursor: e-resize;
  opacity: 0;
  transition: opacity 0.2s;
}
.resize-handle-c {
  position: absolute;
  left:0;
  bottom:0px;
  width:100%;
  height:3px;
  background-color: #409eff;
  cursor: s-resize;
  opacity: 0;
  transition: opacity 0.2s;
}
th:hover .resize-handle-c,
td:hover .resize-handle-r {
  opacity: 1;
}
th:hover .resize-handle-r,
td:hover .resize-handle-c {
  opacity: 1;
}
/* 表头和序号列的定位 */
th, td {
  position: relative;
  padding:5px 5px;
}

/* 表格样式调整 */
table {
  table-layout: fixed;
  border-collapse: collapse;
}
.delete-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  cursor: pointer;
  color: #ff4d4f;
  font-size: 12px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 2px;
  border-radius: 50%;
}

.delete-icon:hover {
  color: #ff7875;
}
</style>